define(function(require, exports){
	var pubjs = require('pubjs');
	var grid  = require('@base/highGrid');
	var util = require('util');
	var $ = require('jquery');
	var adx_map = pubjs.config('channelMap');
	var dspUtil = require('dspUtil');

	/**
	一些说明
		1. 关于竞价类指标：【竞价请求数，出价数，竞得数，竞得率，使用率】
			- RTB活动：有，但要去掉竞价请求数，因为数量太大，而且意义不大
			- RTB活动/尺寸等：无，后端由于特殊原因统计不到，故要隐藏
			- RTB活动/尺寸等/广告位：有
			- RTB活动/广告位/尺寸等：有
			- 监测活动：无

		2. 指标顺序
			竞得率和竞价请求数要放到前排；metricForward参数

		3. 广告位子表格
			RTB和监测下的广告位子表格是不一样的；'mediaAndAd'和'mediaAndAd_Monitor'参数
	**/

	// 指标配置
	var METRICS = ["{front}","{back}","{conversion}","{cost}"];

	// 指标分组
	var METRIC_GROUP = pubjs.config('metricsGroup/spot/tabs');

	// condition 数据转换
	// "[{"campaign_id":23},{"spot_size_id":90030}]" --> ["campaign_id", "spot_size_id"]
	function _getCondition(subParam){
		if(util.isString(subParam)){
			subParam = JSON.parse(subParam);
		}

		var data = [];
		for (var i = 0; i < subParam.length; i++) {
			// 每一组condition参数；类型为对象。
			var group = subParam[i];
			// condition_id
			for(var name in group){
				data.push(name);
			}
		}

		return data;
	}

	// 获取子表格配置
	function _getSubgridItems(config){
		if(config && config.noSubs)
		{
			return [];
		}
		var subParam = config.param;

		// 处理 condition 参数
		if(!subParam.condition){
			pubjs.error(LANG('没有condition参数'));
			return false;
		}

		var count = 0;
		var name = _getCondition(subParam.condition);
		var mapping = ['spot_id', 'referer_domain_id', 'channel_id', 'spot_size_id', 'spot_screen_id'];
		for (var i = 0; i < name.length; i++) {
			if(util.find(mapping, name[i]) != null){
				count++;
			}
		}

		// 层层递减到最后一级时，移除 mediaAndAd 这个子项
		// 子表格通用配置项
		// 说明：子表格的项目不一样，少了创意多了创意包，少了活动。
		var subs = [
			'mediaAndAd', // 区分RTB和监测
			'sweety',
			'whisky',
			'period',
			'frequency',
			'region',
			'product'
		];

		if(count>=4){
			subs.shift();
		}

		return subs;
	}

	// 判断父层中是否有广告位维度，以渲染竞价类指标
	function _isParentHasSpot(param){
		// 处理 condition 参数
		if(!param.condition){
			pubjs.error(LANG('没有condition参数'));
			return false;
		}
		var result = false;
		var name = _getCondition(param.condition);
		for (var i = 0; i < name.length; i++) {
			if(name[i] == 'spot_id'){
				result = true;
			}
		}
		return result;
	}

	// 广告位 -主表格
	var Ads = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'spot/list',
					cols: dspUtil.shield_price([
						//{name:'op',text:LANG("操作"), type: 'op'},
						//{name:'_id',text:"ID", sort: true,align:'center', width: 150,render:'renderId',isRenderWidth: true},
						{name:'decimal_id',text:"ID", sort: true,align:'center', width: 150,render:'renderId',isRenderWidth: true},
						{name:'Name',text:LANG("广告位名称"), type:'index', width: 220,render:'renderName'},
						{name:'AdxId',text:LANG("渠道"), width: 100,align:'left', render: 'renderChannel'},
						'AdvisePrice',
						{name:'Size',text:LANG("尺寸"), render: 'renderPixelSize',width:80}
					]),
					// 媒体广告位、创意、落地页，时段、频次、地域、客户端、产品、活动
					subs: ['mediaAndAd', 'creative', 'whisky', 'period', 'frequency', 'region', 'client', 'product', 'campaign'],
					subFilter: 'subFilter',
					tab: pubjs.config('metricsGroup/spot/tabs'),
					default_metrics : pubjs.config('metricsGroup/spot/metrics'),
					metricForward: ["request_num"],
					param: {
						queryByGo: true
						,order: 'impressions|-1,clicks|-1'
						,decimal: true
					},
					reqType: 'websocket',
					gridName: 'spot'
				}
			);
			this.Super('init', arguments);
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		},
		onData: function(err)
		{
			if(err)
			{
				pubjs.alert(err && err.message);
			}

			this.Super('onData', arguments);
		},
		renderId: function(i, val, data, con, tr){
			var html = $('<div/>').text(val).attr('title', val);
			var len = String(val).length;
			if(len < 9 && len > 5){
				con.width = 100;
			}else if(len <= 5){
				con.width = 60;
			}
			return html;
		},
		renderName: function(i, val, data, con){
			val = val || '-';
			var hasIcon = data.SystemDeduct > 0;
			var ret = [];
			var width = con.width - 20;
			if(hasIcon) {
				ret.push('<em class="costPrice"></em>');
			}
			if(data.PageUrl) {
				var isMatch = data.PageUrl.match(/^(http|https):\/\//g);
				var PageUrl = (isMatch == null) ? ('http://' + data.PageUrl) : data.PageUrl;
				ret.push('<a style="width: ' + width + 'px" class="uk-text-truncate tl fl" target="_blank" href="'+ PageUrl +'" title="'+val+'">'+val+'</a>');
			}
			else {
				if(data.AdChannelId == 2){
					var href = '#ads/edit/' + data._id;
					ret.push('<a href="'+href+'" target="_blank" style="width: ' + width + 'px" class="text-truncate tl fl" title="'+val+'">'+val+'</a>');
				}else{
					ret.push('<div style="width: ' + width + 'px" class="uk-text-truncate tl fl" title="'+val+'">'+val+'</div>');
				}

			}

			return $(ret.join(''));
		},
		renderChannel: function(i, val, data, con){
			return $('<div class="text-truncate"/>').text(adx_map[val] || data.ChannelName || LANG('未知'));
		}
	});
	exports.ads = Ads;

	// 媒体
	var Media = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'massMedia/list',
					cols: [
						{name:'op',text:LANG("操作"), type: 'op'},
						{name:'_id',text:"ID", sort: true,width:50},
						{name:'Name',text:LANG("媒体"), type:'index', width: 200, render:'renderName'},
						{name:'AdSubChannelName',text:LANG("所属渠道"),  width: 150,align:'left'}
						// {name:'referer_domain_name',text:LANG("域名"), type:'index', width: 200}
					],
					// 媒体广告位、创意包、落地页、时段、频次、地域、产品
					subs: ['mediaAndAd', 'sweety', 'whisky', 'period', 'frequency', 'region', 'product'],
					subFilter: 'subFilter',
					default_metrics : pubjs.config('defaultMetrics'),
					reqType: 'websocket',
					exportParam: 'medium',
					param: {
						queryByGo: true
						,order: 'impressions|-1'
					},
					gridName: 'media'
				}
			);

			if(util.exist(this.parseSubsCondition(config), 'whisky')){
				util.extend(true, config.get(), {
					'tab':{'cost': null, 'front': null}
				});
			}

			this.Super('init', arguments);
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				if (sub.type === 'sweety'){
					sub.iconBtn.toggle(data.type != 2);
				}
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		},
		renderName: function(i, val, data, con){
			val = val || '-';
			return $('<div class="uk-text-truncate tl fl" title="'+val+'">'+val+'</div>').width(con.width-20);
		}
	});
	exports.media = Media;

	// 尺寸
	var MainSize = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {
					url: 'spot/size',
					cols: [
						//{name:'op',text:LANG("操作"), type: 'op'},
						{type: 'id'},
						//{name:'_id',text:"ID", sort: true},
						{name:'spot_size_id',text: LANG('广告尺寸'), type:'index', render: 'renderPixelSize', width: 200}
						// {name:'referer_domain_name',text:LANG("域名"), type:'index', width: 200}
					],
					// 媒体广告位、创意包、落地页、时段、频次、地域、产品
					subs: ['mediaAndAd', 'sweety', 'whisky', 'period', 'frequency', 'region', 'product'],
					default_metrics : pubjs.config('defaultMetrics').concat(['win_rate']),
					tab: pubjs.config('metricsGroup/spot/tabs'),
					reqType: 'websocket',
					exportParam: 'spot/size',
					param: {
						queryByGo: true
						,order: 'impressions|-1'
					},
					gridName: 'spotSize',
					subFilter: 'subFilter'
				}
			);
			this.Super('init', arguments);
		}
		,subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		}
		,renderPixelSize: function(index, value, row, con){
			var text;
			if (!row.Width || !row.Height){
				if(row.Size) {
					text = Math.floor(row.Size/10000) + '*' + (row.Size % 10000);
				}
				else {
					text = '-';
				}
			}else {
				text = row.Width + '*' + row.Height;
			}
			return $('<div class="uk-text-truncate tl fl" title="'+text+'">'+text+'</div>').width(con.width-20);
		}
	});
	exports.mainSize = MainSize;

	/**	  -----  RTB活动/媒体&广告位选项卡 -5个子表格  -----	**/

	// 广告位
	var Spot = grid.base.extend({
		init: function(config){
			config = pubjs.conf(config, {});
			var param = config.get('param');
			if(param && param.condition){
				this.$campaign_id = JSON.parse(param.condition)[0].campaign_id;
			}
			config = pubjs.conf(config, {
					url: 'spot/rtbList',
					param: {decimal: true},
					urlChangePrice: 'campaign/setPremium',
					urlFilterSpot: "campaign/filterSpot",	// 暂停启用广告位
					cols: dspUtil.shield_price([
						// {type: 'id'},
						//{name:'_id',text:"ID",align:'center',sort: true, width: 150, render:'renderId',isRenderWidth: true}, // @todo 要限制宽度
						{name:'decimal_id',text:"ID",align:'center',sort: true, width: 150, render:'renderId',isRenderWidth: true}, // @todo 要限制宽度
						{name:'Name',text:LANG("广告位"), type:'index', width: 200, render: 'renderName'},
						// {name:'ChannelName',text:"渠道", width:60, render:'renderChannel'},
						{name:'Size',text:LANG("尺寸"), render:'renderSize', width:65},
						{name:'set_price',text:LANG("出价"), render:'renderPrice', width: 55},
						{name:'premium',text:LANG("差异出价"), render:'renderPremium', width: 72, align: 'right'}
					], 'set_price'),
					subs: _getSubgridItems(config.get()),
					default_metrics : [
						"impressions","new_impressions","old_impressions","visitors","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"end_cpc","end_cpm","end_cpa","cost",
						"request_num", "win_rate"
					],
					tab: {
						"front": true,
						"back": true,
						"conversion": true,
						"cost": true,
						"bid":{
							"text":LANG('竞价'),
							"cols":[
								"request_num"			// 竞价请求数
								,"bid_num"				// 出价数
								,'bid_rate'				// 出价率
								,"win_num"				// 竞得数
								,"win_rate"				// 竞得率
								,"bid_use_rate"			// 使用率
							]
						}
					},
					hasMenu: true,
					hasBatch: true,
					hasSelect: true,
					auto_load: false,
					// 竞得率和竞价请求数要放在前面
					metricForward: [ "win_rate","request_num"],
					reqType: 'websocket',
					customControl: this.buildStatusFilter,
					exportParam: 'spot',
					subField: 'spot', // 用于子表格作为父行的标识; 因为gridName:ads已经被主表使用了
					gridName: 'RTBCampaignSpot',
					subFilter: 'subFilter'
				}
			);

			if(util.exist(this.parseSubsCondition(config), 'whisky')){
				util.extend(true, config.get(), {
					'tab':{'bid': null, 'cost': null, 'front': null}
				});
			}

			// 第一次reload, 以防止未构建完成就开始reload, 会导致数据不正确, 和指标未配置完成.
			this.$first = true;
			this.Super('init', arguments);
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		},
		// 状态过滤
		buildStatusFilter: function(el){
			$('<label class="fl mt10"/>').text(LANG('状态:')).appendTo(el);
			this.createAsync('ads_filter', '@base/common/input.radioGroup', {
				'target': el,
				'class': 'M-commonRadioGroup M-commonRadioGroup fl mt10 ml10',
				'value': 'all',
				'data': [
					{'text': LANG('所有'), 'value':'all'}
					//{'text': LANG('已暂停'), 'value':'pause'}
					//{'text': LANG('进行中'), 'value':'running'}
				]
			});
		},
		// 响应Radio事件 -广告位状态过滤
		onRadioChange: function(ev){
			var value;
			switch(ev.param){
				case 'pause':
					value = 2;
				break;
				case 'running':
					value = 1;
				break;
				default:
					value = null;
				break;
			}
			if(this.$first) {
				this.reload({
					'subgrid_status': value
				});
			}
			else {
				this.$first = false;
			}
			return false;
		},
		renderId: function(i, val, data, con){
			var html = $('<div class="text-truncate"/>').attr('title', val).text(val);
			var len = String(val).length;
			if(len < 9 && len > 5){
				con.width = 100;
			}else if(len <= 5){
				con.width = 60;
			}
			this.uiBind(html, 'dblclick', function(evt, elm){
				pubjs.clipboard(html, val);
			});
			return html;
		},
		renderName: function(i, val, data, con){
			var status = +data.status;
			var statusClass = 'pause';
			var	iconTitle = LANG('未知状态');

			if(status === 1){
				statusClass = 'running';
				iconTitle = LANG('正常');
			}
			if(status === 0){
				statusClass = 'pause';
				iconTitle = LANG('暂停');
			}

			var html = $([
				'<div class="fl tl text-truncate">',
					'<i title="'+iconTitle+'" class="vAlign_m '+statusClass+' mr5"></i>',
					'<a target="_blank" class="vAlign_m">'+val+'</a>',
				'</div>'
			].join('')).width(180);

			if(data.PageUrl){
				var isMatch = data.PageUrl.match(/^(http|https):\/\//g);
				var PageUrl = (isMatch == null) ? ('http://' + data.PageUrl) : data.PageUrl;
				html.find('a').attr('href', PageUrl);
			}else{
				html.find('a').addClass('cur_d');
			}

			return html;
		},
		renderChannel: function(i, val, data, con){
			return $('<div class="text-truncate"/>').text(adx_map[val] || LANG('未知'));
		},
		renderPremium: function(i, val, row, con){
			var data = {
					'Price'			: +val || 0,
					'spot_id'		: row._id
				};
			var value = this.formatCurrency(val);

			//用户是只读状态 只显示价格 不能编辑
			//var userStatus = pubjs.getUser().current.Status;
			//if(+userStatus === 1){
			//	return value;
			//}

			var dom = $([
				'<div class="text-truncate">',
				'<i class="price-edit"></i>'+ value,
				'</div>'
			].join(''));
			if(!con.noEdit)
			{
				this.uiBind(dom.find('i'), 'click', data, 'eventChangePrice');
			}
			else
			{
				dom.find('.price-edit').removeClass('price-edit');
			}

			return dom;
		},
		renderPrice: function(i, val, row, con){
			var html = $('<div class=""/>').text(this.formatCurrency(val));
			return html;
		},
		renderSize: function(i, val, row, con){
			var text = '-';
			if(row.Size) {
				text = Math.floor(row.Size/10000) + '*' + (row.Size % 10000);
			}
			return $('<div class="text-truncate">'+ text +'</div>');
		},
		eventChangePrice: function(ev, elm){
			this.$tmpData = ev.data;
			var topPriceMod = this.$.changePrice;
			if(!topPriceMod){
				topPriceMod = this.createAsync('changePrice', 'modules/countSelector.base', {
					prefix: "￥",		//字段前缀
					suffix: LANG('元'),//字段后缀
					addCount: 0.5,
					value: this.$tmpData.Price
				}, function(mod){
					mod.show({
						anchor:$(elm).offset(),
						data: this.$tmpData.Price
					});
				});
			}
			else{
				topPriceMod.show({
					anchor:$(elm).offset(),
					data: this.$tmpData.Price
				});
			}
			return false;
		},
		formatCurrency: function(val){
			val = util.round0(val, 2);
			return (LANG("￥"))+util.numberFormat(val);
		},
		onUpdateValue: function(ev){
			if(!util.isNumber(+ev.param)){
				pubjs.alert(LANG('价格信息错误'));
				return false;
			}

			var data = {
				'premium': +ev.param,
				'campaign_id': +this.$campaign_id,
				'spot_id': this.$tmpData.spot_id
			};
			var url = this.getConfig('urlChangePrice');
			pubjs.mc.send(url, data, this.onSaveValue.bind(this));
			return false;
		},
		onSaveValue: function(err, data){
			if(err){
				pubjs.alert(err.message);
			}
			pubjs.alert(LANG('修改成功'));
			this.reload();
			this.$tmpData = {};
		},
		onOperateMenuShow: function(ev){
			var option;
			switch(+ev.param.status){
				case 0:	// 暂停状态
					if(pubjs.checkRight('campaign.spotSaveStart'))
					{
						//option.push({id: 'saveStart', name: LANG('开启*')});
						option = [{id: 'saveStart', name: LANG('开启*')}];
					}
					else
					{
						option = [{id: 'start', name: LANG('开启')}];
					}
				break;
				case 1:	// 正常状态
					option = [{id: 'pause', name: LANG('暂停')}];
				break;
				default:
					pubjs.error('此广告位的状态异常');
				break;
			}

			ev.returnValue = option;
			return false;
		},
		onOperateMenuSelect: function(ev){
			var op = ev.param[0];
			var data = ev.param[1];
			var c = this.getConfig();

			// 获取父层活动id
			var rule = /\"campaign_id\"\:(.*)\}/;
			var condition = c.param.condition;
			var result = condition.match(rule);
			var param = {
				ids: [data._id],
				campaign_id: result[1],
				status: op.key == 'start' ? 1 : 2	// 1为白(开启), 2为黑(关闭),
			};

			if(op.key === 'saveStart')
			{
				param.saveMode = true;
				param.status = 1;
			}

			pubjs.mc.send(c.urlFilterSpot, param, this.onFilterSpot.bind(this));
			return false;
		},
		onBatchShow: function(ev){
			var option;
			if(pubjs.checkRight('campaign.spotSaveStart'))
			{
				option = [{id: 'saveStart', name: LANG('批量开启*')}];
			}
			else
			{
				option = [{id: 'start', name: LANG('批量开启')}];
			}

			option.push({id: 'pause', name: LANG('批量暂停')});
			ev.returnValue = option;
			return false;
		},
		onBatchSelect: function(ev){
			var data = ev.param[0];
			var ids = ev.param[1];
			if(!ids || !ids.length) {
				pubjs.alert(LANG('请先选择广告位'));
				return false;
			}

			var c = this.getConfig();

			// 获取父层活动id
			var rule = /\"campaign_id\"\:(.*)\}/;
			var condition = c.param.condition;
			var result = condition.match(rule);
			var param = {
				ids: ids,
				campaign_id: result[1],
				status: data.key == 'start' ? 1 : 2	// 1为白(开启), 2为黑(关闭),
			};

			if(data.key === 'saveStart')
			{
				param.saveMode = true;
				param.status = 1;
			}

			pubjs.mc.send(c.urlFilterSpot, param, this.onFilterSpot.bind(this));
			return false;
		},
		// 响应过滤广告位事件
		onFilterSpot: function(err, data){
			if(err){
				pubjs.alert('广告位操作失败：'+err.message);
				return false;
			}

			if(data && data.length)
			{
				var info = '';
				util.each(data, function(spot) {
					var prop;
					var text;
					switch(true)
					{
						case spot.hasOwnProperty('Size'):
							text = LANG('尺寸');
							prop = 'Size';
							break;
						case spot.hasOwnProperty('Screen'):
							text = LANG('屏次');
							prop = 'Screen';
							break;
						case spot.hasOwnProperty('SiteDomain'):
							text = LANG('域名');
							prop = 'SiteDomain';
							break;
					}

					info += '\n ' + LANG('%1 广告位在特殊名单里 %2 %3被过滤',spot.Name, spot[prop], text);
				});

				pubjs.alert(LANG('操作成功，但以下广告位在特殊条件里的黑名单依然被过滤，如想开启请到活动编辑里的特殊名单里操作:%1', info));
			}

			this.reload();
		}
	});
	exports.spot = Spot;

	exports.admin_spot = Spot.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				tab: pubjs.config('metricsGroup/arithmetic/tabs'),
				hasSearch: false,
				hasFilter: false,
				hasBatch: false,
				hasExport: false,
				customControl: false,
				hasSelect: false,
				hasMenu: false,
				auto_load: true,
			});

			this.Super('init', arguments);
		}
	});

	// 简单版spot
	var LiteSpot = grid.base.extend({
		init: function(config){
			if(config.param && config.param.condition){
				this.$campaign_id = JSON.parse(config.param.condition)[0].campaign_id;
			}
			config = pubjs.conf(config, {
					url: 'spot/rtbList',
					urlChangePrice: 'campaign/setPremium',
					urlFilterSpot: "campaign/filterSpot",	// 暂停启用广告位
					cols: [
						{type: 'id'},
						// {name:'_id',text:"ID", sort: true}, // @todo 要限制宽度
						{name:'Name',text:LANG("广告位"), type:'index', width: 200, render: 'renderName'},
						{name:'ChannelName',text:"渠道"},
						{name:'Size',text:"尺寸", render:'renderSize', width:70}
					],
					subs: _getSubgridItems(config),
					default_metrics : [
						"impressions","new_impressions","old_impressions","visitors","clicks","click_rate","click_reach_rate",
						"back_pageviews",
						"back_regs","back_reg_rate",
						"cpc","cpm","cpa","cost",
						"request_num", "win_rate"
					],
					tab: {
						'front': {'text': '默认状态下没有选项可选', 'cols': []},
						'back': null,
						'conversion': null,
						'cost': null,
						'bid': null
					},
					hasMenu: true,
					hasBatch: true,
					hasSelect: true,
					auto_load: false,
					// 竞得率和竞价请求数要放在前面
					metricForward: [ "win_rate","request_num"],
					reqType: 'websocket',
					customControl: this.buildStatusFilter,
					exportParam: 'spot',
					subField: 'spot', // 用于子表格作为父行的标识; 因为gridName:ads已经被主表使用了
					gridName: 'RTBCampaignSpot'
				}
			);

			// 第一次reload, 以防止未构建完成就开始reload, 会导致数据不正确, 和指标未配置完成.
			this.$first = true;
			this.Super('init', arguments);
		},
		// 状态过滤
		buildStatusFilter: function(el){
			$('<label class="fl mt10"/>').text(LANG('状态:')).appendTo(el);
			this.createAsync('filter', '@base/common/input.radioGroup', {
				'target': el,
				'class': 'M-commonRadioGroup M-commonRadioGroup fl mt10 ml10',
				'value': 'all',
				'data': [
					{'text': LANG('所有'), 'value':'all'},
					{'text': LANG('已暂停'), 'value':'pause'},
					{'text': LANG('进行中'), 'value':'running'}
				]
			});
		},
		// 响应Radio事件 -广告位状态过滤
		onRadioChange: function(ev){
			var value;
			switch(ev.param){
				case 'pause':
					value = 2;
				break;
				case 'running':
					value = 1;
				break;
				default:
					value = null;
				break;
			}
			if(this.$first) {
				this.reload({
					'subgrid_status': value
				});
			}
			else {
				this.$first = false;
			}
			return false;
		},
		renderName: function(i, val, data, con){
			var status = +data.status;
			var statusClass = 'pause';
			var	iconTitle = LANG('未知状态');

			if(status === 1){
				statusClass = 'running';
				iconTitle = LANG('正常');
			}
			if(status === 0){
				statusClass = 'pause';
				iconTitle = LANG('暂停');
			}
			return $([
				'<div class="fl tl uk-text-truncate">',
					'<i title="'+iconTitle+'" class="vAlign_m '+statusClass+' mr5"></i>',
					'<a target="_blank" href="'+data.PageUrl+'" class="vAlign_m">'+val+'</a>',
				'</div>'
			].join('')).width(con.width -20);
		},
		renderPremium: function(i, val, row, con){
			var data = {
					'Price'			: +val || 0,
					'spot_id'		: row._id
				};
			var value = this.formatCurrency(val);

			//用户是只读状态 只显示价格 不能编辑
			//var userStatus = pubjs.getUser().current.Status;
			//if(+userStatus === 1){
			//	return value;
			//}

			var dom = $([
				'<div class="uk-text-truncate tl fl">',
					'<i class="price-edit mr5"></i>'+ value,
				'</div>'
				].join(''));
			this.uiBind(dom.find('i'), 'click', data, 'eventChangePrice');
			return dom;
		},
		renderPrice: function(i, val, row, con){
			return this.formatCurrency(val);
		},
		renderSize: function(i, val, row, con){
			var text = '-';
			if(row.Size) {
				text = Math.floor(row.Size/10000) + '*' + (row.Size % 10000);
			}
			return $('<div>'+ text +'</div>').width(con.width - 10);
		},
		eventChangePrice: function(ev, elm){
			this.$tmpData = ev.data;
			var topPriceMod = this.$.changePrice;
			if(!topPriceMod){
				topPriceMod = this.createAsync('changePrice', 'modules/countSelector.base', {
					prefix: "￥",		//字段前缀
					suffix: LANG('元'),//字段后缀
					addCount: 0.5,
					value: this.$tmpData.Price
				}, function(mod){
					mod.show({
						anchor:$(elm).offset(),
						data: this.$tmpData.Price
					});
				});
			}
			else{
				topPriceMod.show({
					anchor:$(elm).offset(),
					data: this.$tmpData.Price
				});
			}
			return false;
		},
		formatCurrency: function(val){
			val = util.round0(val, 2);
			return (LANG("￥"))+util.numberFormat(val);
		},
		onUpdateValue: function(ev){
			if(!util.isNumber(+ev.param)){
				pubjs.alert(LANG('价格信息错误'));
				return false;
			}

			var data = {
				'premium': +ev.param,
				'campaign_id': +this.$campaign_id,
				'spot_id': this.$tmpData.spot_id
			};
			var url = this.getConfig('urlChangePrice');
			pubjs.mc.send(url, data, this.onSaveValue.bind(this));
			return false;
		},
		onSaveValue: function(err, data){
			if(err){
				pubjs.alert(err.message);
			}
			pubjs.alert(LANG('修改成功'));
			this.reload();
			this.$tmpData = {};
		},
		onOperateMenuShow: function(ev){
			var option;
			switch(+ev.param.status){
				case 0:	// 暂停状态
					option = [{id: 'start', name: LANG('开启')}];
				break;
				case 1:	// 正常状态
					option = [{id: 'pause', name: LANG('暂停')}];
				break;
				default:
					pubjs.error('此广告位的状态异常');
				break;
			}

			ev.returnValue = option;
			return false;
		},
		onOperateMenuSelect: function(ev){
			var op = ev.param[0];
			var data = ev.param[1];
			var c = this.getConfig();

			// 获取父层活动id
			var rule = /\"campaign_id\"\:(.*)\}/;
			var condition = c.param.condition;
			var result = condition.match(rule);

			pubjs.mc.send(c.urlFilterSpot, {
				//ids: [+data._id],
				ids: [data._id],
				campaign_id: result[1],
				status: op.key == 'start' ? 1 : 2	// 1为白(开启), 2为黑(关闭),
			}, this.onFilterSpot.bind(this));

			return false;
		},
		onBatchShow: function(ev){
			ev.returnValue = [
				{id: 'pause', name: LANG('批量暂停')},
				{id: 'start', name: LANG('批量开始')}
			];
			return false;
		},
		onBatchSelect: function(ev){
			var data = ev.param[0];
			var ids = ev.param[1];
			if(!ids || !ids.length) {
				pubjs.alert(LANG('请先选择广告位'));
				return false;
			}

			var c = this.getConfig();

			// 获取父层活动id
			var rule = /\"campaign_id\"\:(.*)\}/;
			var condition = c.param.condition;
			var result = condition.match(rule);

			pubjs.mc.send(c.urlFilterSpot, {
				ids: ids,
				campaign_id: result[1],
				status: data.key == 'start' ? 1 : 2	// 1为白(开启), 2为黑(关闭),
			}, this.onFilterSpot.bind(this));

			return false;
		},
		// 响应过滤广告位事件
		onFilterSpot: function(err, data){
			if(err){
				pubjs.error('广告位操作失败：'+err.message);
				return false;
			}

			this.reload();
		}
	});
	exports.liteSpot = LiteSpot;

	// 媒体域名
	var Domain = grid.base.extend({
		init: function(config){
			// 只有当父层有Spot维度时候，才会有竞价类指标
			var isParantSpot = _isParentHasSpot(config.param);

			config = pubjs.conf(config, {
				hasBatch: true,
				hasSelect: true,
				key: 'referer_domain_id',
				url: 'domain/list',
				urlFilterSpot: 'campaign/filterDomain',
				param: {
					order: 'impressions|-1'
				},
				cols: [
					{name:'op',text:LANG("操作"), type: 'op'},
					{type: 'id'},
					{name:'referer_domain_name',text:LANG("媒体域名"), type:'index', width: 200, render: 'renderName'}
				],
				default_metrics : pubjs.config('defaultMetrics'),
				tab: isParantSpot ? METRIC_GROUP : null,
				metrics: isParantSpot ? METRICS.concat(['{bid}']): METRICS,
				subs: _getSubgridItems(config),
				hasMenu: true,
				labels: {pause: LANG('过滤此域名'), start: LANG('启用该域名'), saveStart: LANG('启用该域名*')},
				saveStartRight: 'campaign.domainSaveStart',
				reqType: 'websocket',
				gridName: 'domain',
				auto_load: 'false',
				subFilter: 'subFilter'
			});

			switch(this.parseSubsCondition(config).pop()){
				case 'campaign':
				case 'package':
				case 'platform':
					util.extend(true, config.get(), {
						'tab':{'bid': null}
					});
					break;
				case 'product':
					util.extend(true, config.get(), {
						'tab':{'cost': null, 'front': null, 'bid': null}
					});
					break;
			}

			this.Super('init', arguments);
		},
		renderName: function(i, val, data, con){
			var status = +data.status;
			var statusClass = 'pause';
			var	iconTitle = LANG('未知状态');

			if(status === 1){
				statusClass = 'running';
				iconTitle = LANG('正常');
			}
			if(status === 0){
				statusClass = 'pause';
				iconTitle = LANG('此域名已被过滤');
			}
			var href = 'http://'+data.referer_domain_name;
			return $([
				'<div class="fl tl">',
					'<div class="uk-text-truncate">',
						'<i title="'+iconTitle+'" class="vAlign_m '+statusClass+' mr5"></i>',
						'<span class="vAlign_m" title="'+data.referer_domain_title+'">'+data.referer_domain_title+'</span>',
					'</div>',
					'<a class="ml20" target="_blank" href="'+href+'">'+data.referer_domain_name+'</a>',
				'</div>'
			].join('')).width(con.width -20);
		},
		onOperateMenuShow: function(ev){
			var option;
			var c = this.getConfig();
			switch(+ev.param.status){
				case 0:	// 暂停状态
					if(pubjs.checkRight(c.saveStartRight))
					{
						option = [{id: 'saveStart', name: c.labels.saveStart}];
					}
					else
					{
						option = [{id: 'start', name: c.labels.start}];
					}
				break;
				case 1:	// 正常状态
					option = [{id: 'pause', name: c.labels.pause}];
				break;
				default:
					pubjs.error('数据异常,status='+ ev.param.status);
				break;
			}

			ev.returnValue = option;
			return false;
		},
		onOperateMenuSelect: function(ev){
			var op = ev.param[0];
			var c = this.getConfig();
			var key = c.key;
			var data = ev.param[1][key];

			// 获取父层活动id
			var rule = /\"campaign_id\"\:(.*)\}/;
			var condition = c.param.condition;
			var result = condition.match(rule);
			var param = {
				ids: [data],
				campaign_id: result[1],
				status: op.key == 'start' ? 1 : 2	// 1为白(开启), 2为黑(关闭),
			};

			if(op.key == 'saveStart')
			{
				param.saveMode = true;
				param.status = 1;
			}

			pubjs.mc.send(c.urlFilterSpot, param, this.onFilterSpot.bind(this));

			return false;
		},
		onFilterSpot: function(err, data){
			if(err){
				pubjs.error('广告位操作失败：'+err.message);
				return false;
			}

			this.reload();
		},
		onBatchShow: function(ev){
			var c = this.getConfig();
			var option;
			if(pubjs.checkRight(c.saveStartRight))
			{
				option = [{id: 'saveStart', name: LANG('批量开启*')}];
			}
			else
			{
				option = [{id: 'start', name: LANG('批量开启')}];
			}

			option.push({id: 'pause', name: LANG('批量暂停')});
			ev.returnValue = option;
			return false;
		},
		onBatchSelect: function(ev){
			var data = ev.param[0];
			var ids = ev.param[1];
			if(!ids || !ids.length) {
				pubjs.alert(LANG('请先选择广告位'));
				return false;
			}

			var c = this.getConfig();

			// 获取父层活动id
			var rule = /\"campaign_id\"\:(.*)\}/;
			var condition = c.param.condition;
			var result = condition.match(rule);
			var param = {
				ids: ids,
				campaign_id: result[1],
				status: data.key == 'start' ? 1 : 2	// 1为白(开启), 2为黑(关闭),
			};

			if(data.key === 'saveStart')
			{
				param.saveMode = true;
				param.status = 1;
			}

			pubjs.mc.send(c.urlFilterSpot, param, this.onFilterSpot.bind(this));
			return false;
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		},
	});
	exports.domain = Domain;

	// 尺寸
	var Size = Domain.extend({
		init: function(config){
			var isParantSpot = _isParentHasSpot(config.param);

			config = pubjs.conf(config, {
					url: 'spot/size',
					urlFilterSpot: 'campaign/filterSize',
					cols: [
						{"type":"id"},
						{name:'Size',text: LANG('广告尺寸'), type:'index', render: 'renderPixelSize', width: 200}
					],
					subFilter: 'subFilter',
					default_metrics : pubjs.config('defaultMetrics'),
					hasMenu: true,
					subs: _getSubgridItems(config),
					metrics: isParantSpot ? METRICS.concat(['{bid}']): METRICS,
					tab: isParantSpot ? METRIC_GROUP : null,
					labels: {pause: LANG('过滤此尺寸'), start: LANG('启用该尺寸'), saveStart: LANG('启用该尺寸*')},
					saveStartRight: 'campaign.sizeSaveStart',
					reqType: 'websocket',
					exportParam: 'spot/size',
					gridName: 'spotSize',
					auto_load: 'false'
				}
			);

			switch(this.parseSubsCondition(config).pop()){
				case 'campaign':
					util.extend(true, config.get(), {
						'tab':{'bid': null}
					});
					break;
				case 'medium':
					util.extend(true, config.get(), {
						'tab':{'bid': null, 'cost': null}
					});
					break;
			}

			Domain.Super(this, 'init', arguments);
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		},
		renderPixelSize: function(index, value, row, con){
			var status = +row.status;
			var statusClass = 'pause';
			var	iconTitle = LANG('未知状态');

			if(status === 1){
				statusClass = 'running';
				iconTitle = LANG('正常');
			}
			if(status === 0){
				statusClass = 'pause';
				iconTitle = LANG('此尺寸已被过滤');
			}

			var text;
			if (!row.Width || !row.Height){
				if(row.Size) {
					text = Math.floor(row.Size/10000) + '*' + (row.Size % 10000);
				}
				else {
					text = '-';
				}
			}else {
				text = row.Width + '*' + row.Height;
			}

			var html = $([
				'<div class="uk-text-truncate fl vAlign_m">',
					'<i title="'+iconTitle+'" class="vAlign_m '+statusClass+' mr5"></i>',
					'<span class="vAlign_m">'+text+'</span>',
				'</div>'
			].join(''));
			return html.width(con.width-20);
		}
	});
	exports.size = Size;

	// 简单版size
	var LiteSize = Domain.extend({
		init: function(config){
			var isParantSpot = _isParentHasSpot(config.param);

			config = pubjs.conf(config, {
					url: 'spot/size',
					urlFilterSpot: 'campaign/filterSize',
					cols: [
						{"type":"id"},
						{name:'Size',text: LANG('广告尺寸'), type:'index', render: 'renderPixelSize', width: 200}
					],
					subFilter: 'subFilter',
					default_metrics : pubjs.config('defaultMetrics'),
					hasMenu: true,
					subs: _getSubgridItems(config),
					metrics: isParantSpot ? METRICS.concat(['{bid}']): METRICS,
					labels: {pause: LANG('过滤此尺寸'), start: LANG('启用该尺寸')},
					reqType: 'websocket',
					exportParam: 'spot/size',
					gridName: 'spotSize',
					auto_load: 'false',
					tab: {
						'front': null,
						'back': null,
						'conversion': null,
						'cost': null,
						'bid': null
					}
				}
			);
			Domain.Super(this, 'init', arguments);
		},
		renderPixelSize: function(index, value, row, con){
			var status = +row.status;
			var statusClass = 'pause';
			var	iconTitle = LANG('未知状态');

			if(status === 1){
				statusClass = 'running';
				iconTitle = LANG('正常');
			}
			if(status === 0){
				statusClass = 'pause';
				iconTitle = LANG('此尺寸已被过滤');
			}

			var text;
			if (!row.Width || !row.Height){
				if(row.Size) {
					text = Math.floor(row.Size/10000) + '*' + (row.Size % 10000);
				}
				else {
					text = '-';
				}
			}else {
				text = row.Width + '*' + row.Height;
			}

			var html = $([
				'<div class="uk-text-truncate fl vAlign_m">',
					'<i title="'+iconTitle+'" class="vAlign_m '+statusClass+' mr5"></i>',
					'<span class="vAlign_m">'+text+'</span>',
				'</div>'
			].join(''));
			return html.width(con.width-20);
		}
	});
	exports.liteSize = LiteSize;

	// 屏次
	exports.screens = Domain.extend({
		init: function(config){
			var isParantSpot = _isParentHasSpot(config.param);
			config = pubjs.conf(config, {
					url: 'spot/screen',
					urlFilterSpot: 'campaign/filterScreen',
					cols: [
						{"type":"id"},
						{name:'_id',text: LANG('ID'),align:'center',width:80},
						{name:'ScreenName',text: LANG('屏次'), type:'index', render: 'renderName', width:200}
					],
					default_metrics : pubjs.config('defaultMetrics'),
					hasMenu: true,
					subs: _getSubgridItems(config),
					metrics: isParantSpot ? METRICS.concat(['{bid}']): METRICS,
					tab: isParantSpot ? METRIC_GROUP : null,
					labels: {pause: LANG('过滤此屏次'), start: LANG('启用该屏次'), saveStart: LANG('启用该屏次*')},
					saveStartRight: 'campaign.screenSaveStart',
					reqType: 'websocket',
					exportParam: 'spot/screen',
					gridName: 'spotScreen',
					subFilter: 'subFilter'
				}
			);

			switch(this.parseSubsCondition(config).pop()){
				case 'medium':
					util.extend(true, config.get(), {
						'tab':{'cost': null}
					});
					break;
			}

			Domain.Super(this, 'init', arguments);
		},
		subFilter: function(subs, data){
			// 帐号行业类型：1 游戏，有产品版；2 电商，无产品版
			var user = pubjs.getUser();
			var trade = user.current.ExchangeInfo.CategoryId;

			util.each(subs, function(sub){
				// 有产品版的账号才有产品子表格
				if (sub.type === 'product') {
					sub.iconBtn.toggle(trade == 1);
				}
			});
		},
		renderName: function(i, val, data, con){
			var status = +data.status;
			var statusClass = 'pause';
			var iconTitle = LANG('未知状态');

			if(status === 1){
				statusClass = 'running';
				iconTitle = LANG('正常');
			}
			if(status === 0){
				statusClass = 'pause';
				iconTitle = LANG('此屏次已被过滤');
			}
			return $([
				'<div class="fl tl uk-text-truncate">',
					'<i title="'+iconTitle+'" class="vAlign_m '+statusClass+' mr5"></i>',
					'<span class="vAlign_m">'+val+'</span>',
				'</div>'
			].join('')).width(con.width -20);
		}
	});

	//var EXCHANGE = pubjs.config('exchange');

	// 渠道
	exports.channel = grid.base.extend({
		init: function(config){
			var isParantSpot = _isParentHasSpot(config.param);

			config = pubjs.conf(config, {
					url: 'channel/list',
					urlFilterSpot: 'campaign/filterDomain',
					key: 'channel_id',
					cols: [
						{"type":"id"},
						{name:'channel_id',text: LANG('渠道ID'), align: 'center',width:80},
						{name:'ChannelName',text: LANG('渠道'),align:'left', width:100}
					],
					default_metrics : pubjs.config('defaultMetrics'),
					subs: _getSubgridItems(config),
					metrics: isParantSpot ? METRICS.concat(['{bid}']): METRICS,
					tab: isParantSpot ? METRIC_GROUP : null,
					labels: {pause: LANG('过滤此渠道'), start: LANG('启用该渠道')},
					reqType: 'websocket',
					exportParam: 'channel',
					noSubs: false,
					gridName: 'spotChannel'
				}
			);

			if(util.exist(this.parseSubsCondition(config), 'whisky')){
				util.extend(true, config.get(), {
					'tab':{'bid': null, 'front': null}
				});
			}

			this.Super('init', arguments);
		}
	});
});
